import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/login/login_password_page.dart';
import 'package:flutter_syt/domain/login/widgets/login_input_decorator.dart';
import 'package:flutter_syt/domain/login/widgets/login_protocol.dart';
import 'package:flutter_syt/domain/widgets/code_form_field.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_common.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_comment.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/common_button.dart';

class RegisterEmailPage extends StatefulWidget {
  @override
  RegisterEmailPageState createState() => RegisterEmailPageState();
}

class RegisterEmailPageState extends State<RegisterEmailPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  final _formEmailKey = GlobalKey<FormState>();
  FocusNode phoneEmailFocusNode = FocusNode();
  FocusNode pwdEmailFocusNode = FocusNode();
  FocusNode codeEmailFocusNode = FocusNode();
  TextEditingController _textEditingController = TextEditingController();
  String _codeEmail = '', _passwordEmail = '', _email = '';

  bool _agree = false;

  bool blurBackground = false;

  // bool pwsPhoneobscureText = true;
  bool pwsEmailobscureText = true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Form(
      key: _formEmailKey,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 0, horizontal: 30),
        child: Column(
          children: [
            BlurRectWidget(
              TextFormField(
                enableInteractiveSelection: false,
                maxLength: 60,
                inputFormatters: [
                  FilteringTextInputFormatter.deny(appContext.emojiRegexp)
                ],
                autofocus: false,
                controller: _textEditingController,
                focusNode: phoneEmailFocusNode,
                style: const TextStyle(color: Colors.black, fontSize: 14),
                cursorColor: ThemeColor.primaryColor,
                decoration: LoginInputDecoration(
                    hintText: S.of(context).enter_mobile_email),
                onSaved: (val) {
                  if (val != null) {
                    _email = val;
                    appContext.storage.setString("login_email", _email);
                  }
                },
                // obscureText: true,
                keyboardType: TextInputType.text,
                autocorrect: false,
              ),
            ),
            const SizedBox(
              height: 24,
            ),
            CodeFormField(
              tagStr: 'registeremail',
              focusNode: codeEmailFocusNode,
              getSmsCode: getEmailCode,
              decoration: LoginInputDecoration(),
              onSaved: (val) => _codeEmail = val!,
            ),
            const SizedBox(
              height: 24,
            ),
            TextFormField(
              enableInteractiveSelection: false,
              maxLength: 16,
              autofocus: false,
              inputFormatters: [
                FilteringTextInputFormatter.deny(appContext.emojiRegexp)
              ],
              focusNode: pwdEmailFocusNode,
              style: const TextStyle(
                color: Colors.black,
                fontSize: 14,
              ),
              cursorColor: ThemeColor.primaryColor,
              obscureText: pwsEmailobscureText,
              decoration: LoginInputDecoration(
                hintText: S.of(context).Password_8_16,
                suffixIcon: GestureDetector(
                  onTap: ClickUtils.debounce(() {
                    if (mounted) {
                      setState(() {
                        pwsEmailobscureText = !pwsEmailobscureText;
                      });
                    }
                  }),
                  child: SizedBox(
                      width: 20,
                      child: Center(
                        child: Image.asset(
                          pwsEmailobscureText
                              ? 'assets/images/comment_obscureText_open.png'
                              : 'assets/images/comment_obscureText_close.png',
                          width: 20,
                          color: Colors.white,
                          height: pwsEmailobscureText ? 20 : 14,
                        ),
                      )),
                ),
              ),
              validator: (val) {
                if (val != null) {
                  if (!UtilsComment.checkPasswordFormal(val)) {
                    customShowToast(S.of(context).passwordToast_8_16);
                    return '';
                  }
                }
                return null;
              },
              onSaved: (val) => _passwordEmail = val!,
              // obscureText: true,
              keyboardType: TextInputType.text,
              autocorrect: false,
            ),
            const SizedBox(
              height: 30,
            ),
            LoginProtocol(onChange: (value) {
              setState(() {
                _agree = value;
              });
            }),
            Container(
              margin: const EdgeInsets.only(top: 30),
              width: double.infinity,
              // child: ElevatedButton(
              //     child: Text(
              //       S.of(context).sign_up2,
              //       style: TextStyle(fontWeight: FontWeight.bold),
              //     ),
              //     onPressed: ClickUtils.debounce(
              //       () async {
              //         await _submit();
              //       },
              //     )),
              child: CommonButton.expend(
                title: S().sign_up2,
                onAsyncClick: () async {
                  await _submit();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<bool> getEmailCode() async {
    if (!_agree) {
      customShowToast(S.of(context).privacy_policy_consent_t);
      return false;
    }
    final form = _formEmailKey.currentState;
    form!.save();
    if (!RegexUtil.isEmail(_email)) {
      customShowToast(S.of(context).enter_valid_email);
      return false;
    }
    // DLog(_email);
    // bool isVertifica = await UtilsOther.checkShowVertification(
    //     account: _email, type: '2', context: context);
    // if (isVertifica == false) {
    //   return false;
    // }
    // // return false;

    try {
      bool res = await API.shared.login.getEmailCode(_email, 'register');
      customShowToast(S().send_code_2);
      return res;
    } catch (e) {
      await UtilsOther.showCustomShowError(e);
      // if (e is DioError) {
      //   customShowError(e.message);
      // } else {
      //   customShowError(S().network_error);
      // }
      return true;
    }
  }

  Future _register() async {
    await API.shared.login.emailRegister(_email, _passwordEmail, _codeEmail,
        device: (Platform.isIOS
            ? appContext.iOSInfo.identifierForVendor
            : appContext.andriodInfo.androidId));
    // .emailRegister(_phone.areaCode, _phone.phone, _password, _code);
  }

  Future _submit() async {
    // Navigator.of(context).popUntil((route) {
    //   var name = route.settings.name;
    //   if (name != null) {
    //     return name.startsWith(GlobalData.pageFrom);
    //   }
    //   return route.isFirst;
    // });
    // Navigator.of(context).pop();
    // Navigator.of(context).pop();
    // return;
    final form = _formEmailKey.currentState;
    if (!_agree) {
      customShowToast(S.of(context).privacy_policy_consent_t);
      return;
    }
    if (form!.validate()) {
      form.save();
      if (!RegexUtil.isEmail(_email)) {
        customShowToast(S.current.enter_valid_email);
        return;
      }

      try {
        await loading(_register, text: S.of(context).on_register);
        GlobalData.bindPush();
        GlobalData.getIndexSetting();
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        customShowSuccess(S.of(context).register_success);
      } catch (e) {
        UtilsOther.showCustomShowError(e);
      }
      // customShowSuccess(S.of(context).register_success);

      // Navigator.of(context).popUntil((route) => route.isFirst);
    }
  }

  @override
  void initState() {
    super.initState();
    String cacheEmail = appContext.storage.getString("login_email") ?? '';
    if (cacheEmail.isNotEmpty) {
      _textEditingController.text = cacheEmail;
    }
    // EditableTextState
  }

  @override
  void dispose() {
    super.dispose();
    phoneEmailFocusNode.dispose();
    codeEmailFocusNode.dispose();
    pwdEmailFocusNode.dispose();
  }

  @override
  void didUpdateWidget(RegisterEmailPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
